﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Linq;
using System.Threading.Tasks;
using System.Windows.Forms;
using DevExpress.XtraEditors;
using Lamex.Library;
using Lamex.Library.CommonClass;
using Lamex.mMachine.Model;
using Lamex.Base;
using Lamex.mMachine.BLL;
using System.IO;
using System.Collections;

namespace Lamex.mMachine.UI
{
    public partial class frmMAC_MT_Content_Input : frmBaseChild
    {
        string strSql;
        DataTable dt;
        string path = @"\\tx-fs10.lamex.com\TX-FS1\IMA\MES\ShareResource\FAMA_Image\";//图片保存位置
        string paths = "";//实际图片路径
        public static FrmMAC_ShowPicture fm = null;

        public frmMAC_MT_Content_Input()
        {
            InitializeComponent();
        }
        private void frmMAC_MT_Content_Input_Resize(object sender, EventArgs e)
        {
            splitContainerControl1.SplitterPosition = this.Width - 330;
        }

        private void frmMAC_MT_Content_Input_Load(object sender, EventArgs e)
        {
            try { base.InitButtons(); } catch { }//初始化标准功能，因要应用于RibbonForm，所以加入异常处理
            gridView1.OptionsBehavior.Editable = false;
            //文字左对齐，直接在设计器中设置
            //vGridControl1.Appearance.RecordValue.HAlignment = DevExpress.Utils.HorzAlignment.Near;

            setvGridControlRepository();

            setGridControlData();

            //遍历并设置自动列宽
            setGridViewColumnAutoWidth();
        }

        //设置控件可选项
        private void setvGridControlRepository()
        {
            vGridControl1.OptionsBehavior.Editable = false;
            vGridControl1.DataSource = null;

            //获取维修人信息
            DataTable dt = Common.GetDataTable.GetTable_RepairMan();

            //RESPONSE_PERSON
            DevExpress.XtraEditors.Repository.RepositoryItemSearchLookUpEdit lookup_response = new DevExpress.XtraEditors.Repository.RepositoryItemSearchLookUpEdit();
            lookup_response.NullText = string.Empty;
            if (dt.Select("MAINTAIN_FLAG=1").Length > 0)
            {
                DataTable dt_ResponsePerson = dt.Select("MAINTAIN_FLAG=1").CopyToDataTable().DefaultView.ToTable(true, new string[] { "WORKER_NO", "WORKER_NAME" });
                lookup_response.DataSource = dt_ResponsePerson;
                lookup_response.ValueMember = "WORKER_NO";
                lookup_response.DisplayMember = "WORKER_NO";
            }        
            vGridControl1.Rows["rowACTUAL_MAINTAINER"].Properties.RowEdit = lookup_response;
            //加载SELECT [WORKER_NO],[WORKER_NAME] FROM [LamexMES_FAMA].[dbo].[MT_Resource_Worker_List] WHERE MAINTAIN_FLAG=1

            DevExpress.XtraEditors.Repository.RepositoryItemComboBox comboBox_state = new DevExpress.XtraEditors.Repository.RepositoryItemComboBox();
            comboBox_state.TextEditStyle = DevExpress.XtraEditors.Controls.TextEditStyles.DisableTextEditor;
            string[] reportList = new string[] { "无维修价值", "已完成维修" };
            foreach (var item in reportList)
            {
                comboBox_state.Items.Add(item);
            }
            vGridControl1.Rows["rowMAINTAIN_RESULT"].Properties.RowEdit = comboBox_state;
            //加载选项“已停机,未停机"，不允许用户后期增加选项，所以静态加载

            DevExpress.XtraEditors.Repository.RepositoryItemComboBox comboBox_failType = new DevExpress.XtraEditors.Repository.RepositoryItemComboBox();
            comboBox_failType.TextEditStyle = DevExpress.XtraEditors.Controls.TextEditStyles.DisableTextEditor;
            string[] failList = Common.GetDataTable.GetArray_ActualType().Split(',');
            foreach (var item in failList)
            {
                comboBox_failType.Items.Add(item);
            }
            vGridControl1.Rows["rowACTUAL_FAILURE_TYPE"].Properties.RowEdit = comboBox_failType;
            //加载表[Sys_ControlValueOption].[FIELD_NAME]=FAMA_MT_FAILURE_TYPE，即“机械,电气,皮带,网络,其他”拆分结果
            //因允许用户后期增加选项，所以动态加载
            //SELECT[FIELD_VALUE_OPTION] FROM[LamexMESManager].[dbo].[Sys_ControlValueOption] WHERE FIELD_NAME = 'FAMA_MT_FAILURE_TYPE'

            DevExpress.XtraEditors.Repository.RepositoryItemMemoEdit memoEdit = new DevExpress.XtraEditors.Repository.RepositoryItemMemoEdit();
            vGridControl1.Rows["rowFAILURE_CAUSE"].Properties.RowEdit = memoEdit;
            vGridControl1.Rows["rowACTUAL_WORK_CONTENT"].Properties.RowEdit = memoEdit;
            vGridControl1.Rows["rowIMPROVE_PLAN"].Properties.RowEdit = memoEdit;
            //vGridControl1.Rows["rowMAINTAIN_REMARK"].Properties.RowEdit = memoEdit;
            //注册图片点击事件
            repositoryItemPictureEdit1.Click += RepositoryItemPictureEdit1_Click;
            repositoryItemPictureEdit1.DoubleClick += RepositoryItemPictureEdit1_DoubleClick;
        }

        private void RepositoryItemPictureEdit1_DoubleClick(object sender, EventArgs e)
        {
            OpenFileDialog file = new OpenFileDialog();
            file.InitialDirectory = ".";
            file.Filter = "JPG图片|*.jpg|PNG图片|*.png|GIF图片|*.gif";
            file.ShowDialog();
            if (file.FileName != string.Empty)
            {
                try
                {
                    string pathname = file.FileName;   //获得文件的绝对路径
                    Bitmap myBmp = new Bitmap(pathname);//图片定义    
                    //把图片解析成流
                    byte[] buffer = PhotoImageInsert(myBmp);
                    //图片保存到本地
                    paths = "";
                    paths = path + DateTime.Now.ToString("yyyyMMddHHmmssfff") + ".jpg";
                    WriteBytesToFile(paths, buffer);
                    //显示图片
                    ShowPic(paths);
                }
                catch (Exception ex)
                {
                    MessageBox.Show(ex.Message);
                }
            }
        }

        private void RepositoryItemPictureEdit1_Click(object sender, EventArgs e)
        {
            if (!string.IsNullOrEmpty(paths))
            {
                if (fm == null)
                {
                    FrmMAC_ShowPicture frmMAC_ShowPicture = new FrmMAC_ShowPicture(paths);
                    frmMAC_ShowPicture.Show();
                    fm = frmMAC_ShowPicture;
                }
                else
                {
                    fm.Close();
                    fm = null;
                }
            }
        }
        public byte[] PhotoImageInsert(System.Drawing.Image imgPhoto)
        {
            //将Image转换成流数据，并保存为byte[] 
            MemoryStream mstream = new MemoryStream();
            imgPhoto.Save(mstream, System.Drawing.Imaging.ImageFormat.Bmp);
            byte[] byData = new Byte[mstream.Length];
            mstream.Position = 0;
            mstream.Read(byData, 0, byData.Length);
            mstream.Close();
            return byData;
        }
        //图片保存到本地
        public void WriteBytesToFile(string fileName, byte[] content)
        {
            FileStream fs = new FileStream(fileName, FileMode.Create);
            BinaryWriter w = new BinaryWriter(fs);
            try
            {
                w.Write(content);
            }
            finally
            {
                fs.Close();
                w.Close();
            }
        }
        private void setGridViewColumnAutoWidth()
        {
            gridView1.OptionsView.ColumnAutoWidth = false;
            for (int i = 0; i < gridView1.Columns.Count; i++)
            {
                gridView1.BestFitColumns();
                if (i == 2)
                {
                    gridView1.Columns[2].Width = 20;
                }
                else
                {
                    gridView1.Columns[i].BestFit();//自动列宽    
                }
            }
        }

        private void radioGroup1_SelectedIndexChanged(object sender, EventArgs e)
        {
            setGridControlData();
        }

        //加载所有厂内维修清单
        private void setGridControlData()
        {
            strSql = @"SELECT c.MAINTAIN_NO,
c.MACHINE_NO,
MACHINE_DESC,
ACTUAL_MAINTAINER,
ACTUAL_FAILURE_TYPE,
ACTUAL_WORK_CONTENT,
MAINTAIN_RESULT,
FAILURE_CAUSE,
IMPROVE_PLAN,
MAINTAIN_REMARK,
CONFIRM_PERSON,
PROCESS_PLAN,
c.UPDATE_TIME,
c.UPDATE_USER,
FLAG_BLANK
FROM
(SELECT a.MAINTAIN_NO,MACHINE_NO,ACTUAL_MAINTAINER,ACTUAL_FAILURE_TYPE,FLAG_BLANK,
ACTUAL_WORK_CONTENT,MAINTAIN_RESULT,FAILURE_CAUSE,IMPROVE_PLAN,MAINTAIN_REMARK,CONFIRM_PERSON,PROCESS_PLAN,
b.UPDATE_TIME,b.UPDATE_USER
FROM [LamexMES_FAMA].[dbo].[MT_Maintain_Record] AS a
LEFT JOIN 
[LamexMES_FAMA].[dbo].[MT_Maintain_Detail] AS b
ON a.MAINTAIN_NO=b.MAINTAIN_NO) AS c
LEFT JOIN 
[LamexMESManager].[dbo].[FAMA_Account_Basic_Info] AS d
ON c.MACHINE_NO=d.MACHINE_NO
WHERE PROCESS_PLAN='内部维修' AND CONFIRM_PERSON IS NOT NULL ORDER BY UPDATE_TIME ";

            gridControl1.DataSource = null;
            dt = Lamex.Base.BaseBuildSql.GetDataTableBySql(strSql);
            gridControl1.DataSource = dt;

            //自动勾选无需填值的数据
            DataRow[] rows = dt.Select("ISNULL(FLAG_BLANK,'')='1'");
            if (rows.Length > 0)
            {
                foreach (var item in rows)
                {
                    int iIndex = dt.Rows.IndexOf(item);
                    gridView1.SelectRow(iIndex);
                }

            }
            //遍历并设置自动列宽
            setGridViewColumnAutoWidth();

            vGridControl1.DataSource = null;
        }

        private void sbtnSave_Click(object sender, EventArgs e)
        {
            //MessageBox.Show("1、保存[右侧编辑区]当前数据至[LamexMES_FAMA].[dbo].[MT_Maintain_Detail]；" +
            //    "\r\n" + "2、保存前检查用户是否有数据修改权限");
            ////数据修改权限逻辑：检查当前用户是否有表修改权限，通过[LamexMESManager].[dbo].[Sys_DataAuthority]比对
            try
            {
                //if (!Common.CRUDHelper.IsExistList("MT_Maintain_Detail", "LamexMES_FAMA")) return;

                string strMAINTAIN_NO = vGridControl1.Rows["rowMAINTAIN_NO"].Properties.Value != null ?
                    vGridControl1.Rows["rowMAINTAIN_NO"].Properties.Value.ToString() : "";//维修编号
                string strACTUAL_MAINTAINER = vGridControl1.Rows["rowACTUAL_MAINTAINER"].Properties.Value != null ?
                    vGridControl1.Rows["rowACTUAL_MAINTAINER"].Properties.Value.ToString() : "";//实际维修人
                string strACTUAL_FAILURE_TYPE = vGridControl1.Rows["rowACTUAL_FAILURE_TYPE"].Properties.Value != null ?
                    vGridControl1.Rows["rowACTUAL_FAILURE_TYPE"].Properties.Value.ToString() : "";//实际维修类型
                string strACTUAL_WORK_CONTENT = vGridControl1.Rows["rowACTUAL_WORK_CONTENT"].Properties.Value != null ?
                    vGridControl1.Rows["rowACTUAL_WORK_CONTENT"].Properties.Value.ToString() : "";//维修内容
                string strMAINTAIN_RESULT = vGridControl1.Rows["rowMAINTAIN_RESULT"].Properties.Value != null ?
                    vGridControl1.Rows["rowMAINTAIN_RESULT"].Properties.Value.ToString() : "";//实际维修结果
                string strFAILURE_CAUSE = vGridControl1.Rows["rowFAILURE_CAUSE"].Properties.Value != null ?
                    vGridControl1.Rows["rowFAILURE_CAUSE"].Properties.Value.ToString() : "";
                string strIMPROVE_PLAN = vGridControl1.Rows["rowIMPROVE_PLAN"].Properties.Value != null ?
                    vGridControl1.Rows["rowIMPROVE_PLAN"].Properties.Value.ToString() : "";
                //string strMAINTAIN_REMARK = vGridControl1.Rows["rowMAINTAIN_REMARK"].Properties.Value != null ?
                //    vGridControl1.Rows["rowMAINTAIN_REMARK"].Properties.Value.ToString() : "";
                string strMAINTAIN_REMARK = paths;
                string strUPDATE_TIME = DateTime.Now.ToString();
                string strUPDATE_USER = Lamex.Common.Loginer.CurrentUser.Account;

                //跨数据库，底层不支持
                //MT_Maintain_DetailInfo model = new MT_Maintain_DetailInfo();
                //model.MAINTAIN_NO = strMAINTAIN_NO;
                //model.ACTUAL_MAINTAINER = strACTUAL_MAINTAINER;
                //model.ACTUAL_FAILURE_TYPE = strACTUAL_FAILURE_TYPE;
                //model.ACTUAL_WORK_CONTENT = strACTUAL_WORK_CONTENT;
                //model.MAINTAIN_RESULT = strMAINTAIN_RESULT;
                //model.FAILURE_CAUSE = strFAILURE_CAUSE;
                //model.IMPROVE_PLAN = strIMPROVE_PLAN;
                //model.MAINTAIN_REMARK = strMAINTAIN_REMARK;
                //model.UPDATE_TIME = DateTime.Now;
                //model.UPDATE_USER = Lamex.Common.Loginer.CurrentUser.AccountName;

              
                //if (string.IsNullOrEmpty(strACTUAL_MAINTAINER))
                //{
                //    DevExpress.XtraEditors.XtraMessageBox.Show("实际维修人为空,不允许保存！", "提示", MessageBoxButtons.OK);
                //    return;
                //}
                //if (string.IsNullOrEmpty(strACTUAL_FAILURE_TYPE))
                //{
                //    DevExpress.XtraEditors.XtraMessageBox.Show("实际维修类型为空,不允许保存！", "提示", MessageBoxButtons.OK);
                //    return;
                //}
                //if (string.IsNullOrEmpty(strACTUAL_WORK_CONTENT))
                //{
                //    DevExpress.XtraEditors.XtraMessageBox.Show("维修内容为空,不允许保存！", "提示", MessageBoxButtons.OK);
                //    return;
                //}
                //if (string.IsNullOrEmpty(strMAINTAIN_RESULT))
                //{
                //    DevExpress.XtraEditors.XtraMessageBox.Show("实际维修结果为空,不允许保存！", "提示", MessageBoxButtons.OK);
                //    return;
                //}
                //if (BaseFactory<MT_Maintain_Detail>.Instance.InsertKey(model))
                //{
                string strFlag = "";
                //无需填写维修内容
                int[] iRowList = gridView1.GetSelectedRows();
                //foreach (var item in iRowList)
                //{
                //    strMAINTAIN_NO = Convert.ToString(gridView1.GetRowCellValue(item, "MAINTAIN_NO"));
                //}
                //目前只提供单条勾选保存的逻辑
                if (iRowList.Length > 0)
                {
                    int iRow = gridView1.FocusedRowHandle;
                    if(iRowList.Contains(iRow))                 
                    {
                        strFlag = "1";
                        strMAINTAIN_NO = Convert.ToString(gridView1.GetRowCellDisplayText(iRow, "MAINTAIN_NO"));
                    }
                }
                if (string.IsNullOrEmpty(strMAINTAIN_NO))
                {
                    DevExpress.XtraEditors.XtraMessageBox.Show("维修编号为空,不允许保存！", "提示", MessageBoxButtons.OK);
                    return;
                }

                if (Common.CRUDHelper.Insert_MT_Maintain_Detail(strMAINTAIN_NO, strACTUAL_MAINTAINER, strACTUAL_FAILURE_TYPE, strACTUAL_WORK_CONTENT,
                    strMAINTAIN_RESULT, strFAILURE_CAUSE, strIMPROVE_PLAN, strMAINTAIN_REMARK, strUPDATE_TIME, strUPDATE_USER, strFlag))
                {
                    DevExpress.XtraEditors.XtraMessageBox.Show("维修记录修改成功！", "提示", MessageBoxButtons.OK);
                    setGridControlData();
                    //每次保存后锁定信息输入
                    vGridControl1.OptionsBehavior.Editable = false;
                    for (int i = 0; i < vGridControl1.Rows.Count; i++)
                    {
                        vGridControl1.SetCellValue(vGridControl1.Rows[i], 0, null);
                    }
                }
                else
                {
                    DevExpress.XtraEditors.XtraMessageBox.Show("维修记录修改失败！", "提示", MessageBoxButtons.OK);
                    return;
                }

            }
            catch (Exception ex)
            {
                XtraMessageBox.Show(ex.Message, "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return;
            }
        }

        private void gridControl1_DoubleClick(object sender, EventArgs e)
        {
            SetVGridControl();
        }

        public override void DoEdit(Lamex.Interface.IButtonInfo sender)
        {
            SetVGridControl();
        }

        public override void DoView(Lamex.Interface.IButtonInfo sender)
        {
            setGridControlData();
        }

        public override void DoSave(Lamex.Interface.IButtonInfo sender)
        {
            sbtnSave_Click(null, null);
        }
        private void SetVGridControl()
        {
            //不提供单击浏览操作，浏览、编辑共用操作
            vGridControl1.OptionsBehavior.Editable = true;
            //获取当前行的数据
            int iRow = gridView1.FocusedRowHandle;
            string strMAINTAIN_NO = gridView1.GetRowCellDisplayText(iRow, "MAINTAIN_NO").ToString();//维修编号
            string strMACHINE_NO = gridView1.GetRowCellDisplayText(iRow, "MACHINE_NO").ToString();//设备编号
            string strMACHINE_DESC = gridView1.GetRowCellDisplayText(iRow, "MACHINE_DESC").ToString();//设备描述
            string strACTUAL_MAINTAINER = gridView1.GetRowCellDisplayText(iRow, "ACTUAL_MAINTAINER").ToString();//实际维修人
            string strACTUAL_FAILURE_TYPE = gridView1.GetRowCellDisplayText(iRow, "ACTUAL_FAILURE_TYPE").ToString();//实际故障类别
            string strACTUAL_WORK_CONTENT = gridView1.GetRowCellDisplayText(iRow, "ACTUAL_WORK_CONTENT").ToString();//实际维修内容
            string strMAINTAIN_RESULT = gridView1.GetRowCellDisplayText(iRow, "MAINTAIN_RESULT").ToString();//维修结果
            string strFAILURE_CAUSE = gridView1.GetRowCellDisplayText(iRow, "FAILURE_CAUSE").ToString();//故障原因
            string strIMPROVE_PLAN = gridView1.GetRowCellDisplayText(iRow, "IMPROVE_PLAN").ToString();//预防及改善措施
          
            string strUPDATE_TIME = gridView1.GetRowCellDisplayText(iRow, "UPDATE_TIME").ToString();//更新时间
            string strUPDATE_USER = gridView1.GetRowCellDisplayText(iRow, "UPDATE_USER").ToString();//更新用户


            //把数据显示到右边的VGridControl
            vGridControl1.Rows["rowMAINTAIN_NO"].Properties.Value = strMAINTAIN_NO;
            vGridControl1.Rows["rowMACHINE_NO"].Properties.Value = strMACHINE_NO;
            vGridControl1.Rows["rowMACHINE_DESC"].Properties.Value = strMACHINE_DESC;
            vGridControl1.Rows["rowACTUAL_MAINTAINER"].Properties.Value = strACTUAL_MAINTAINER;
            vGridControl1.Rows["rowACTUAL_FAILURE_TYPE"].Properties.Value = strACTUAL_FAILURE_TYPE;

            vGridControl1.Rows["rowACTUAL_WORK_CONTENT"].Properties.Value = strACTUAL_WORK_CONTENT;
            vGridControl1.Rows["rowMAINTAIN_RESULT"].Properties.Value = strMAINTAIN_RESULT;
            vGridControl1.Rows["rowFAILURE_CAUSE"].Properties.Value = strFAILURE_CAUSE;
            vGridControl1.Rows["rowIMPROVE_PLAN"].Properties.Value = strIMPROVE_PLAN;
            //显示图片
            string strMAINTAIN_REMARK = ((System.Data.DataView)gridView1.DataSource).Table.Rows[iRow]["MAINTAIN_REMARK"].ToString();//备注
            paths = strMAINTAIN_REMARK;//传值给全局图片路径变量
            ShowPic(strMAINTAIN_REMARK);
            //Hashtable Images = new Hashtable();
            //Image img = null;
            //if (!string.IsNullOrEmpty(strMAINTAIN_REMARK))
            //{
            //    img = System.Drawing.Image.FromFile(strMAINTAIN_REMARK);
            //    string fileName = "";
            //    //先求出最后出现这个字符的下标
            //    int index = strMAINTAIN_REMARK.LastIndexOf('\\');
            //    //从下一个索引开始截取
            //    fileName = strMAINTAIN_REMARK.Substring(index + 1);
            //    Images.Add(fileName, img);
            //    vGridControl1.Rows["rowMAINTAIN_REMARK"].Properties.Value = Images[fileName];
            //}

            vGridControl1.Rows["rowUPDATE_TIME"].Properties.Value = strUPDATE_TIME;
            vGridControl1.Rows["rowUPDATE_USER"].Properties.Value = strUPDATE_USER;

            vGridControl1.FocusedRow = vGridControl1.Rows["rowACTUAL_MAINTAINER"];
        }

        private void gridView1_CustomDrawColumnHeader(object sender, DevExpress.XtraGrid.Views.Grid.ColumnHeaderCustomDrawEventArgs e)
        {
            if (e.Column != null && e.Column.Caption == "Selection")
                e.Info.Caption = "无需填写维修履历";
        }
        //显示图片
        private void ShowPic(string filepath)
        {
            Hashtable Images = new Hashtable();
            Image img = null;
            vGridControl1.Rows["rowMAINTAIN_REMARK"].Properties.Value = null;
            if (!string.IsNullOrEmpty(filepath))
            {
                img = System.Drawing.Image.FromFile(filepath);
                string fileName = "";
                //先求出最后出现这个字符的下标
                int index = filepath.LastIndexOf('\\');
                //从下一个索引开始截取
                fileName = filepath.Substring(index + 1);
                Images.Add(fileName, img);
                vGridControl1.Rows["rowMAINTAIN_REMARK"].Properties.Value = Images[fileName];
            }
        }
        private void gridView1_CustomUnboundColumnData(object sender, DevExpress.XtraGrid.Views.Base.CustomColumnDataEventArgs e)
        {
            if (e.Column.FieldName == "MAINTAIN_REMARKES" && e.IsGetData)
            {
                Hashtable Images = new Hashtable();
                if (dt.Rows.Count > 0)
                {
                    for (int i = 0; i < dt.Rows.Count; i++)
                    {
                        string strMaintainNo_e = ((DataRowView)e.Row).Row.ItemArray[0].ToString();
                        Image img = null;
                        string strFilePath = dt.Rows[i]["MAINTAIN_REMARK"].ToString();
                        string strMaintainNo = dt.Rows[i]["MAINTAIN_NO"].ToString();
                        if (strMaintainNo_e != strMaintainNo)
                            continue;
                        if (!string.IsNullOrEmpty(strFilePath))
                        {
                            img = System.Drawing.Image.FromFile(strFilePath);
                            //先求出最后出现这个字符的下标
                            int index = strFilePath.LastIndexOf('\\');
                            //从下一个索引开始截取
                            string fileName = strFilePath.Substring(index + 1);
                            Images.Add(fileName, img);
                            e.Value = Images[fileName];
                        }
                    }
                }             
            }
        }

        private void gridView1_Click(object sender, EventArgs e)
        {
            if (fm != null)
            {
                fm.Close();
                fm = null;
            }
        }

        private void sbtnView_Click(object sender, EventArgs e)
        {
            DoView(null);
        }
    }
}